vim9script noclear

var tempfile: string = tempname()
prop_type_add("GitBlameVim", { 'highlight': 'Conceal'})

export def GitCmd(cmd: string): void
	var file = expand('%:t')

	if empty(file) || !empty(&bufhidden) 
		return
	endif

	$"git --no-pager show HEAD:./{file}"
	->job_start({
		cwd: fnamemodify(resolve(@%), ":p:h"),
		out_io: "file",
		out_name: tempfile,
		exit_cb: (job, status) => {
			if cmd == "Read"
				silent! exec $"leftabove diffsplit {tempfile} | :%diffput | setl nobuflisted |setl bufhidden=delete | :q"
			else
				silent! exec $"leftabove diffsplit {tempfile} | keepalt file fugitive://{@%} | setf {&ft} | setl nobuflisted | setl bufhidden=delete"
				win_execute(win_getid(winnr('#')), "redraw")
			endif
		}
	})
enddef

export def GitSum()
	var filename = expand('%:t')
	var line = line('.')
	var cmd = $"git --no-pager log -1 --date=relative --pretty=format:\"@@@ %h %an (%cd) %s \" -L {line},+1:./{filename}"

	if !filename->empty()
		if !empty(prop_list(line, {types: ["GitBlameVim"]}))
			prop_remove({type: "GitBlameVim"})
		else
			cmd->job_start({
				cwd: fnamemodify(resolve(@%), ":p:h"),
				out_cb: (ch, msg) => msg[0 : 2] != "@@@" ??
					prop_add(line, 0, {'type': 'GitBlameVim', 'text': msg[3 : ], 'text_align': 'after', 'text_wrap': 'wrap'})
			})
		endif
	endif
enddef

def CommitHandler(dir: string, file: string, job: job, status: number)
	var [cmd, str] = ['', '']
	var strlist = readfile(g:fzf_tempfile)

	popup_close(g:fzf_winnr)

	if strlist->empty()
		return
	endif

	str = split(strlist[0], ' ')[0]

	if empty(file)
		$"git --no-pager show {str}"
			->job_start({
				cwd: dir,
				out_io: "file", out_name: tempfile,
				exit_cb: (_, _) => {
					silent! exe $"vertical leftabove split {tempfile} | setl nobuflisted nomod noma| setf git"
				}
			})
	else
		$"git --no-pager show {str}:./{file}"
			->job_start({
				cwd: dir,
				out_io: "file", out_name: tempfile,
				exit_cb: (_, _) => {
					silent! exec $"lockmarks vertical leftabove diffsplit {tempfile} |set ft={&ft}|setl nobuflisted nomod noma"
				}

			})
	endif
enddef

export def Commit(...strlist: list<string>)
	var [file, dir, cmd, term] = ['', '', '', {}]
	var arg: string = "--preview='git show --name-only {1}'"

	if strlist->empty()
		dir = fnamemodify(resolve(@%), ":p:h")
	else
		file = fnamemodify(resolve(expand(strlist[-1])), ":t")
		dir = fnamemodify(resolve(expand(strlist[-1])), ":p:h")
	endif

	if empty(file)
		cmd = "git log --color=always '--format=%C(auto)%h%d %s %C(green)%cr'"
	else
		cmd = $"git log --color=always '--format=%C(auto)%h%d %s %C(green)%cr' --follow ./{file}"
	endif

	term = {
		'cmd': cmd, 'arg': arg, 'cwd': dir,
	}

	fzf#Run(term, function(CommitHandler, [dir, file]))
enddef
